<template>
  <div>
    <!-- 文件处理列表 -->
    <div class="mt-15px grid grid-cols-1 gap-2">
      <div
        v-for="(doc, index) in modelValue.list"
        :key="index"
        class="flex items-center py-4px px-12px border-l-4 border-l-[#409eff] rounded-sm shadow-sm hover:bg-[#ecf5ff] transition-all duration-300"
      >
        <!-- 文件图标和名称 -->
        <div class="flex items-center min-w-[200px] mr-10px">
          <Icon icon="ep:document" class="mr-8px text-[#409eff]" />
          <span class="text-[13px] text-[#303133] break-all">{{ doc.name }}</span>
        </div>

        <!-- 处理进度 -->
        <div class="flex-1">
          <el-progress
            :percentage="doc.progress || 0"
            :stroke-width="10"
            :status="isProcessComplete(doc) ? 'success' : ''"
          />
        </div>

        <!-- 分段数量 -->
        <div class="ml-10px text-[13px] text-[#606266]">
          分段数量：{{ doc.count ? doc.count : '-' }}
        </div>
      </div>
    </div>

    <!-- 底部完成按钮 -->
    <div class="flex justify-end mt-20px">
      <el-button
        :type="allProcessComplete ? 'success' : 'primary'"
        :disabled="!allProcessComplete"
        @click="handleComplete"
      >
        完成
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { KnowledgeSegmentApi, KnowledgeSegmentProcessVO } from '@/api/ai/knowledge/segment'

const props = defineProps({
  modelValue: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['update:modelValue'])
const parent = inject('parent') as any
const pollingTimer = ref<number | null>(null) // 轮询定时器 ID，用于跟踪和清除轮询进程

/** 判断文件处理是否完成 */
const isProcessComplete = (file) => {
  return file.progress === 100
}

/** 判断所有文件是否都处理完成 */
const allProcessComplete = computed(() => {
  return props.modelValue.list.every((file) => isProcessComplete(file))
})

/** 完成按钮点击事件处理 */
const handleComplete = () => {
  if (parent?.exposed?.handleBack) {
    parent.exposed.handleBack(true)
  }
}

const getProcessList = async () => {
  try {
    // 1. 调用 API 获取处理进度
    const documentIds = props.modelValue.list.filter((doc) => doc.id).map((doc) => doc.id)
    if (documentIds.length === 0) {
      return
    }

    const result: KnowledgeSegmentProcessVO[] =
      await KnowledgeSegmentApi.getKnowledgeSegmentProcessList(documentIds)

    const updatedList = props.modelValue.list.map((doc) => {
      const processInfo = result.find((processInfo) => processInfo.documentId === doc.id)
      if (processInfo) {
        // 计算百分比
        const progress =
          processInfo.embeddingCount && processInfo.count
            ? Math.floor((processInfo.embeddingCount / processInfo.count) * 100)
            : 0
        return {
          ...doc,
          count: processInfo.count || 0,
          progress: progress
        }
      }
      return doc
    })

    emit('update:modelValue', { ...props.modelValue, list: updatedList })

    // 尚未分片入库结束，继续轮询
    if (!updatedList.every((doc) => isProcessComplete(doc))) {
      pollingTimer.value = window.setTimeout(getProcessList, 3000)
    }
  } catch (error) {
    console.error('获取处理进度失败:', error)
    pollingTimer.value = window.setTimeout(getProcessList, 5000)
  }
}

/** 组件挂载时开始轮询 */
onMounted(() => {
  // 1. 初始化进度为 0
  const initialList = props.modelValue.list.map((doc) => ({
    ...doc,
    progress: 0
  }))

  emit('update:modelValue', {
    ...props.modelValue,
    list: initialList
  })

  // 2. 开始轮询获取进度
  getProcessList()
})

/** 组件卸载前清除轮询 */
onBeforeUnmount(() => {
  // 清除定时器
  if (pollingTimer.value) {
    clearTimeout(pollingTimer.value)
    pollingTimer.value = null
  }
})
</script>

<style scoped lang="scss"></style>
